<template>
	<view class="wrap bg-white">
		<view class="cu-bar bg-blue flex justify-center align-center"><view class="text-Abc">登录</view></view>
		<view class="content">
			<view class="top-box">
				<view class="cu-avatar radius logo" style="background-image: url(../../static/img/leaf.png)"></view>
				<view class="title text-black text-bold">欢迎登录</view>
			</view>
			<view class="cu-form-group margin-top">
				<view class="title">用户名</view>
				<input type="text" v-model="loginForm.username" placeholder="请输入用户名" autocomplete="off" />
			</view>
			<view class="cu-form-group">
				<view class="title">密码</view>
				<input type="password" v-model="loginForm.password" placeholder="请输入密码" autocomplete="off" />
			</view>
			<view class="cu-form-group">
				<view class="title">验证码</view>
				<input type="text" v-model="loginForm.code" placeholder="请输入验证码" autocomplete="off" />
				<image title="看不清？点击换一张" :src="codeImgSrc" class="verification-code" @click="fetchCode" />
			</view>
			<view class="padding flex flex-direction">
				<button @click="handleLogin" class="cu-btn bg-blue lg">登录</button>
				<button class="cu-btn bg-grey margin-tb-sm lg" @click="toRegister">注册</button>
			</view>
		</view>
		<view class="bottom">
			<view class="hint text-grey text-sm">
				登录代表同意
				<text class="text-blue">Lamb 用户协议、隐私政策，</text>
				并授权使用您的账号信息（如昵称、头像、收获地址）以便您统一管理
			</view>
		</view>
	</view>
</template>

<script>
import JSEncrypt from '@/lib/jsencrypt.min.js';
import urls from '@/api/urls.js';
import { mapMutations, mapState } from 'vuex';
import { loginApi, fetchUserInfoApi } from '../../api/http';
export default {
	data() {
		return {
			loginForm: {
				username: '',
				password: '',
				uuid: '',
				code: ''
			},
			codeImgSrc: '',
			publicKey: '',
			redirect: ''
		};
	},
	onLoad(option) {
		this.redirect = option.redirect;
		uni.getStorage({
			key: 'token',
			success: data => {
				const _token = data.data;
				fetchUserInfoApi({ token: _token })
					.then(res => {
						this.setUserInfo(res.data);
						this.setToken(_token);
						uni.switchTab({
							url: '../home/home'
						});
					})
					.catch(err => {
						console.log(err)
						this.removeLoginInfo();
					});
			}
		});
	},
	onShow: function() {
		this.fetchCode();
	},
	computed: {
		...mapState({
			userInfo: state => state.userInfo,
			token: state => state.token
		})
	},
	methods: {
		...mapMutations(['setToken', 'setUserInfo', 'removeLoginInfo']),
		fetchCode() {
			uni.request({
				url: urls.getCodeUrl,
				method: 'GET',
				responseType: 'ArrayBuffer',
				success: res => {
					this.codeImgSrc = 'data:image/jpg;base64,' + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
					this.publicKey = res.header.sign;
					this.loginForm.uuid = res.header.uuid;
				}
			});
		},
		encryptPassword(pass) {
			let jse = new JSEncrypt();
			jse.setPublicKey(this.publicKey);
			return jse.encrypt(pass);
		},
		showToastWithMsg(msg) {
			uni.showToast({
				title: msg,
				duration: 1000,
				icon: 'none'
			});
		},
		handleLogin() {
			if (this.loginForm.username === '') {
				this.showToastWithMsg('请输入用户名');
				return;
			}
			if (this.loginForm.password === '') {
				this.showToastWithMsg('请输入密码');
				return;
			}
			if (this.loginForm.code === '') {
				this.showToastWithMsg('请输入验证码');
				return;
			}
			let loginFormCopy = Object.assign({}, this.loginForm);
			loginFormCopy.password = this.encryptPassword(loginFormCopy.password);
			loginApi(loginFormCopy)
				.then(res => {
					this.setToken(res.data);
					fetchUserInfoApi({ token: res.data }).then(res2 => {
						this.setUserInfo(res2.data);
						if (this.redirect && this.redirect != '') {
							uni.navigateTo({
								url: this.redirect
							});
						} else {
							uni.switchTab({
								url: '../home/home'
							});
						}
					});
				})
				.catch(err => {
					console.log(err);
					this.fetchCode();
					this.loginForm.code = '';
				});
		},
		toRegister() {
			uni.navigateTo({
				url: '../register/register'
			});
		}
	}
};
</script>

<style lang="scss" scoped>
html,
body,
#app {
	height: 100%;
}
page {
	background-color: #ffffff !important;
}
.wrap {
	height: 100%;
	.content {
		width: 100%;
		height: 100%;
		.top-box {
			width: 100%;
			height: 300rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: space-around;
			.logo {
				width: 150rpx;
				height: 150rpx;
				border-radius: 20rpx;
			}
			.title {
				font-size: 35rpx;
			}
		}
		.verification-code {
			height: 80rpx;
			width: 250rpx;
			object-fit: contain;
		}
	}
	.bottom {
		margin-top: 240rpx;
		text-align: center;
	}
}
</style>
